const User = require('../model/User');
var express = require('express');
// 数据验证模块，
const validator = require('validator');
const Dbset = require('../model/db');
const setting = require('../setting');
var router = express.Router();

exports.zhuce = (req, res, next) => {
    let name = req.body.username;
    let password = req.body.password;
    let num = req.body.num

    let error = '';

    if (!validator.matches(name, /^[T][a-zA-Z0-9_]{4,11}$/, 'g')) {
        error = '用户名不合法，以字母T开头，数字、字母、_';
    }
    if (!validator.matches(password, /(?!^\\d+$)(?!^[a-zA-Z]+$)(?!^[_#@]+$).{3,11}/, 'g')) {
        error = '密码不合法，长度为5-11';
    }
    if (!validator.matches(num, /^[0-9]{3,11}$/, 'g')) {
        error = '密码不合法，长度为5-11';
    }
    if (error) {
        return res.json({
            error: 1,
            message: error
        });
    }

    console.log(req.body)
    User.findOne({
        username: name
    }).then((user) => {
        console.log(name);
        if (user) {
            return res.json({ error: 1, message: '用户名已存在' });
        }
        let newPsd = Dbset.encrypt(password, setting.PSDkey);
        req.body.password = newPsd;

        Dbset.addOne(User, req, res, '注册成功!!');

    }).catch((err) => {
        res.end(err);
    })


}
exports.denglu = (req, res, next) => {
    // console.log(req.body);

    // // 服务端进行数据验证
    let name = req.body.username;
    let password = req.body.password;


    // // 错误数据 / 验证失败的数据
    let error = '';

    if (!validator.matches(name, /^[T][a-zA-Z0-9_]{4,11}$/, 'g')) {
        error = '用户名不合法，以字母T开头，数字、字母、_';
    }
    if (!validator.matches(password, /(?!^\\d+$)(?!^[a-zA-Z]+$)(?!^[_#@]+$).{3,11}/, 'g')) {
        error = '密码不合法，长度为5-11';
    }
    if (error) {
        return res.json({
            error: 1,
            message: error
        });
    }
    // // 密码加密
    let newPsd = Dbset.encrypt(password, setting.PSDkey);
    req.body.password = newPsd;

    User.findOne({
        username: name,
    }).then((user) => {
        if (!user) {
            return res.json({ error: 1, message: '用户名不存在,请注册' });
        }
        // 存储数据
        if (user.password != req.body.password) {
            return res.json({ error: 1, message: '密码错误,请重新输入' });
        }
        req.session.user = user
        res.json({ error: 0, message: '登录成功' })

    }).catch((err) => {
        res.json({ error: 1, message: err });
    })


}
exports.logoing = (req, res, next) => {
    // console.log('123')
    // console.log(req.session.user) //ok
    var data = req.session.user
    if (data == null) {
        res.json({ error: 1, data: '未登录' })

    } else {
        res.json({ error: 0, data: data })
    }


}
exports.logout = (req, res, next) => {
    // console.log('12+++3')
    // console.log(req.session)
    req.session.user = null
    var data = req.session.user
    res.json({ error: 1, data: data })

}